package com.ccut.xunfeiSpringboot.exception;

import com.ccut.xunfeiSpringboot.common.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ControllerAdvice("com.ccut.xunfeiSpringboot.controller")
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<AjaxResult> handleException(Exception ex) {
        log.error("发生异常：", ex);
        AjaxResult result = AjaxResult.error("服务器内部错误: " + ex.getMessage(), 500);
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseEntity<AjaxResult> handleCustomException(CustomException ex) {
        log.warn("业务异常：{}", ex.getMessage());
        AjaxResult result = AjaxResult.error(ex.getMessage(), Integer.parseInt(ex.getCode()));
        return new ResponseEntity<>(result, HttpStatus.valueOf(Integer.parseInt(ex.getCode())));
    }
}
